<script setup>
import { Chart } from '@antv/g2'

const props = defineProps({
  chartData: {
    type: Array,
    default: () => [],
  },
  planData: {
    type: Object,
    default: () => ({}),
  },
  ready: {
    type: Boolean,
    default: false,
  },
})

let chartInstance = null
const chartDomRef = ref(null)

const state = reactive({
  isInited: false,
})

const fillScheme = {
  paper: 'linear-gradient(-90deg, #01FBEF00 0%, #01FBEF 100%)',
  media: 'linear-gradient(-90deg, #0165D900 0%, #0165D9 100%)',
}
const legendScheme = {
  paper: { fill: '#01FBEF', text: '纸质文件' },
  media: { fill: '#0165D9', text: '多媒体介质' },
}

// 初始化渲染图表
const createChartView = (container, { height }) => {
  const chart = new Chart({
    container,
    autoFit: true,
    height: height || 173,
    marginLeft: -12,
    marginTop: -6,
  })

  const title = `${new Date().getFullYear()}年度月份统计`

  chart
    .data(props.chartData)
    .encode('x', 'month')
    .encode('y', 'number')
    .encode('color', 'type')
    .scale('x', {
      range: [0, 1],
    })
    .scale('y', {
      nice: true,
      domain: [0, 120],
    })
    .axis('x', {
      title: false,
      labelFormatter: val => `${val}月`,
    })
    .axis('y', {
      title: '(吨)',
      labelFilter: (datum, idx) => idx % 2 === 0,
      gridFilter: (datum, idx) => idx % 2 === 0,
    })
    .title({
      subtitle: title,
      size: -12,
    })
    .theme({ type: 'custom' })
    .style({
      // viewFill: '#4e79a7',
      // plotFill: '#f28e2c',
      // mainFill: '#e15759',
      // contentFill: '#76b7b2',
    })

  chart
    .interval()
    .transform({ type: 'dodgeX' })
    .tooltip({
      title: d => `${d.month}月`,
      items: [{ name: '销毁量', channel: 'y' }],
    })
    .legend('color', {
    /** 让图例在水平和垂直方向上保持居中 */
      // style: {
      //   dx: 200,
      //   paddingLeft: 64,
      //   marginLeft: 64,
      // },
      // x: 200,
      // dx: 200,
      itemMarker: d => () => {
        const { document } = chart.getContext().canvas
        // const group = document.createElement('rect', {
        //   interactive: false,
        //   style: {
        //     x: 0,
        //     y: -30,
        //     width: 240,
        //     height: 60,
        //     // anchor: '0.5 0.5',
        //     fill: '#00000000',
        //     // fillOpacity: 0,
        //   },
        // })
        // const marginLeft = document.createElement('rect', {
        //   style: {
        //     x: 120,
        //     y: -30,
        //     width: 320,
        //     height: 60,
        //     anchor: '0.5 0.5',
        //     // fill: legendScheme[d].fill,
        //     // lineWidth: 8,
        //     radius: 4,
        //   },
        // })
        const rect = document.createElement('rect', {
          style: {
            x: 0,
            y: -30,
            width: 120,
            height: 60,
            anchor: '0.5 0.5',
            fill: legendScheme[d].fill,
            // lineWidth: 8,
            radius: 4,
            marginLfet: 20,
          },
        })
        // const text = document.createElement('text', {
        //   style: {
        //     x: 0,
        //     y: -30,
        //     width: 120,
        //     height: 60,
        //     anchor: '0.5 0.5',
        //     text: legendScheme[d].text,
        //     fontSize: 14,
        //     // fill: legendScheme[d].fill,
        //     // lineWidth: 8,
        //     // radius: 4,
        //   },
        // })
        // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '???', d, span)
        // span.innerText = legendScheme[d].text
        // span.style.display = 'inline-block'
        // group.appendChild(marginLeft)
        // group.appendChild(rect)
        // group.appendChild(text)
        // group.translate(300)
        // rect.translate(400)
        return rect
      },
      itemSpacing: [10, 1, 1],
      itemMarkerSize: 10,
      itemLabelText: (d) => {
        const key = d?.id || d
        // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', 'label?', d)
        return legendScheme[key].text
      },
      // layout: 'grid',
      colPadding: 20,
      layout: {
        justifyContent: 'flex-start',
        alignItems: 'center',
        flexDirection: 'column',
      },
    }).style({
      maxWidth: 6,
      minHeight: 6,
    })
    .style('fill', (d) => {
      return fillScheme[d.type]
    })
  chart.render()

  state.isInited = true

  return chart
}

// 更新图表数据
const updateChartView = (chart) => {
  chart.changeData(props.chartData)

  // 重新渲染
  chart.render()
  // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '更新图表渲染', props.chartData)
}

watch([() => props.chartData, () => props.ready], ([newData, newReady]) => {
  if(state.isInited && chartInstance) {
    // 已经初始化过图表, 直接更新数据
    // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '更新图表数据', newData)
    updateChartView(chartInstance)
  }
  else {
    // 查看数据接口是否已经准备好
    if(props.ready || newReady) {
      if(newData && chartDomRef.value) {
        // 请求数据成功, 初始化图表
        const { width, height } = chartDomRef.value.getBoundingClientRect()
        chartInstance = createChartView(chartDomRef.value, { width, height })
        // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '初始化图表', newData)
      }
      else {
        // 图标数据为空，更新初始化状态, 展示缺省空状态
        state.isInited = true
        // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '图表数据为空')
      }
    }
    else {
      // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '等待数据请求完成', newData)
    }
  }
}, { deep: true, immediate: true })
</script>

<template>
  <section class="chart-destroy-stats">
    <div class="quick-view">
      <div class="sub-title mr-a w-fit">
        销毁排程
      </div>
      <div class="quick-view__item today">
        <span>今日 :</span>
        <span>{{ planData.todayNum || 0 }}</span>
      </div>
      <span class="quick-view__item split" />
      <div class="quick-view__item tomorrow">
        <span>明天 :</span>
        <span>{{ planData.tomNum || 0 }}</span>
      </div>
      <span class="quick-view__item split" />
      <div class="quick-view__item next-tomorrow">
        <span>后天 :</span>
        <span>{{ planData.dayAfterTomNum || 0 }}</span>
      </div>
    </div>
    <div ref="chartDomRef" class="panel-layout panel-layout--chart" />
  </section>
</template>

<style lang='scss' scoped>
.chart-destroy-stats {
  height: 100%;
  padding: 16px 0;

  .quick-view {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 39px;
    padding: 0 18px;
    background: linear-gradient(90deg,rgb(0 157 227 / 30%), rgb(0 157 227 / 0%) 100%);
    border: 1px solid;
    border-radius: 2px;
    border-image: linear-gradient(90deg, #009de3, rgb(0 157 227 / 0%) 43%, #009de3 100%) 1 1;

    .sub-title {
      font-size: 14px;
      font-weight: 600;
      color: transparent;
      background: linear-gradient(180deg,#fff, #a8f9ff 100%);
      background-clip: text;
    }

    &__item {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      // width: 24%;

      span {
        // margin-left: 10px;
        font-size: 14px;

        &:last-child {
          margin-left: 10px;
        }
      }

      &.split {
        // position: absolute;
        // right: 0;
        display: inline-block;
        width: 2px;
        height: 12px;
        margin: 0 24px;
        // content: '';
        background: #009DE3;
      }

      // &.today,&.tomorrow {
      //   &::after {
      //     position: absolute;
      //     right: 0;
      //     display: inline-block;
      //     width: 2px;
      //     height: 12px;
      //     margin: 0 16px;
      //     content: '';
      //     background: #009DE3;
      //   }
      // }

    }
  }
}

.panel-layout {
  &--chart {
    display: flex;
    height: calc(100% - 39px);
    margin-top: 16px;
    transform: translateX(-5px);
  }
}
</style>
